package com.ht.api.task.ad;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.task.Plan;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.db.util.FunctionUtil;
import com.ht.api.db.util.HtUtil;
import com.ht.api.util.HtTagUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 广告任务组准备任务
 * @author asq
 * @createTime 2025年3月15日 13:40:39
 */
@Slf4j
public class ReadyAdTaskGroupTask implements TaskHandler {

	@Override
	public String getName() {
		return "广告任务组准备任务";
	}

	@Override
	public boolean handler(JSONObject requestParam, String groupId, long taskId) {
		// 获取数据源
		String adTaskGroupId = requestParam.getStr("ad_task_group_id");
		long tenantId = requestParam.getLong("tenant_id");
		DataSource ds = DbConfig.useTenantDb(tenantId);
		StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);

		Entity adTaskGroup = Db.createSqlParser("ad_task_group").where("main_id", adTaskGroupId).findOne(ds);
		adTaskGroup.set("status", 2);
		Db.insert(ds, adTaskGroup);

		String planTime = adTaskGroup.getStr("plan_time");

		String adPosition = adTaskGroup.getStr("ad_position");
		if (adPosition.equals("moment")) {
			readyMoment(adTaskGroup, tenantId, planTime);
		} else if (adPosition.equals("private_chat")) {
			long appId = adTaskGroup.getLong("appid");

			List<Entity> dataList = new ArrayList<>();
			DbList taskList = Db.createSqlParser("ad_user_task").select("main_id").where("ad_task_group_id", adTaskGroupId).query(ds);
			for (Entity task : taskList) {
				task.set("status", 2);
				dataList.add(task);
			}

			Db.insertBatchWithStream(config, dataList);

			JSONObject sendMsgParam = JSONUtil.createObj();
			sendMsgParam.set("appid", appId);
			sendMsgParam.set("tenant_id", tenantId);
			sendMsgParam.set("ad_task_group_id", adTaskGroup.getMainId());
			HtTaskExecutor.submitTask(sendMsgParam, new SendMsgTask(), Plan.create().at(planTime));
		}

		log.info("广告任务组准备工作 success......");

		return true;
	}


	public void readyMoment (Entity adTaskGroup, long tenantId, String planTime) {
		DataSource ds = DbConfig.useTenantDb(tenantId);

		String appId = adTaskGroup.getStr("appid");

		String businessContent = adTaskGroup.getStr("business_content");

		if (StrUtil.isNotBlank(businessContent)) {//说明是根据朋友圈的分区标签ID进行发送
			String tagsql = "select tag_id from wx_moment_tag where appid = ? and moment_partition = ? and sys_deleted = 1 and userid in (select userid from wx_moment_user where ad_task_group_id = ?)";
			DbList momentTagList = Db.query(ds, tagsql, appId, businessContent, adTaskGroup.getMainId());

			JSONArray tags = JSONUtil.createArray();
			for (Entity tag : momentTagList) {
				tags.add(tag.getStr("tag_id"));
			}

			JSONObject sendMomentParam = JSONUtil.createObj();
			sendMomentParam.set("appid", appId);
			sendMomentParam.set("tenant_id", tenantId);
			sendMomentParam.set("tagids", tags);
			sendMomentParam.set("ad_task_group_id", adTaskGroup.getMainId());

			HtTaskExecutor.submitTask(sendMomentParam, new SendMomentTask(), Plan.create().at(planTime));

		} else {
			// 调用请求添加企微标签接口，并得到标签ID
			String tagName = HtUtil.getId();

			JSONObject tagParam = JSONUtil.createObj();
			tagParam.set("group_name", "朋友圈临时标签");
			tagParam.set("tag[0].name", tagName);
			tagParam.set("appid", appId);
			tagParam.set("tenant_id", tenantId);
			IFunctionCall funcCall = FunctionUtil.getFunction("WwxTagAddFunctionCall");
			JSONObject obj = (JSONObject)funcCall.execute(tagParam);

			JSONArray tagArr = obj.getByPath("tag_group.tag", JSONArray.class);
			String tagId = tagArr.getJSONObject(0).getStr("id");
			adTaskGroup.set("business_content", tagId);
			Db.insert(ds, adTaskGroup);

			DbList customers = Db.createSqlParser("wx_moment_customer").where("ad_task_group_id", adTaskGroup.getMainId()).query(ds);

			// 批量打标签
			List<HtTagUtil.TagBean> tagDataList = new ArrayList<>();

			JSONArray addTagArr = JSONUtil.createArray();
			addTagArr.add(tagId);
			for (int i = 0; i < customers.size(); i++) {
				Entity customer = customers.get(i);
				// 这里需要循环，给多个外部用户打标签

				HtTagUtil.TagBean tagBean = HtTagUtil.TagBean.builder()
						.appId(appId) // 应用ID
						.userid(customer.getStr("userid")) // 客服ID
						.externalUserid(customer.getStr("openid")) //外部用户ID
						.tags(addTagArr) // 要打的标签ID数组
						.build();
				tagDataList.add(tagBean);
			}


			HtTagUtil.tag(tagDataList, () -> {
				// 打标签任务的回调
				System.err.println("标签打完啦");

				JSONObject sendMomentParam = JSONUtil.createObj();
				sendMomentParam.set("appid", appId);
				sendMomentParam.set("tagids", Arrays.asList(tagId));
				sendMomentParam.set("tenant_id", tenantId);
				sendMomentParam.set("ad_task_group_id", adTaskGroup.getMainId());
				HtTaskExecutor.submitTask(sendMomentParam, new SendMomentTask(), Plan.create().at(planTime));
			});
		}

	}


}
